package fr.inria.arles.temperatureManagement.tempActuator;


import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.sensorboard.peripheral.LEDColor;
import fr.inria.arles.temperatureManagement.SensorConstants;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import fr.inria.arles.temperatureManagement.SensorConstants.*;

/**
 * MIDIlet running on actautor to change temp to the reference temperature.
 *
 * @author ajay chhatwal
 */
public class TempActuator extends MIDlet {

    private static final int HOST_PORT = 68;
       

    /**
     * Called when the app is started.
     *
     * @throws MIDletStateChangeException
     */
    protected void startApp() throws MIDletStateChangeException {
        RadiogramConnection rCon = null;
        Datagram dg = null;
        
        ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs();
        short command;

        
        // Listen for downloads/commands over USB connection
        try {
            
           // Open up a server-side broadcast radiogram connection
                // to listen for reference readings being sent by base station
                rCon = (RadiogramConnection) Connector.open("radiogram://:"
                        + HOST_PORT);
                dg = rCon.newDatagram(rCon.getMaximumLength());
                
            while (true) {
                rCon.receive(dg);

                // Flash an LED to indicate a actuating event
                leds[7].setRGB(255, 255, 255);
                leds[7].setOn();

                command = dg.readShort();     // read the actuator Command
                System.out.println("Need To acutuate Temp.:"+command);
                leds[0].setOff();
                switch(command)
                {
                    case SensorConstants.SWITCH_OFF:
                        leds[0].setColor(LEDColor.GREEN);
                        break;
                    case SensorConstants.RAISE:
                        leds[0].setColor(LEDColor.RED);
                        break;
                    case SensorConstants.LOWER:
                        leds[0].setColor(LEDColor.BLUE);
                        
                        break;
                }
                leds[0].setOn();
                leds[7].setOff();
                
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * This will never be called by the Squawk VM
     */
    protected void pauseApp() {
        
    }

    /**
     * Only called if startApp throws any exception other than
     * MIDletStateChangeException.
     *
     * @throws MIDletStateChangeException
     */
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        
    }
}
